function request(url, options, callback) {
  let { method, body } = options;
  // 添加url前缀
  if (!url.startsWith("https://") && !url.startsWith("http://")) {
    url = url.startsWith("/") ? url.substr(1) : url;
  }
  let option = {
    method,
    url,
    headers: {
      Accept: "application/json",
      Pragma: "no-cache",
      "Cache-Control": "no-cache",
      Expires: 0,
      "Content-Type": "application/json; charset=utf-8",
    },
  };
  const token = window.localStorage.getItem("token");
  if (token) {
    option.headers = option.headers || {};
    option.headers["Authorization"] = `Bearer ${token}`;
  }

  // 参数赋值
  if (["GET", "DELETE"].includes(method)) {
    option.params = body || {};
  } else {
    option.data = body || {};
  }

  axios(option)
    .then((response) => {
      if (response.data.error) return showError(response.data.message);
      callback(response.data);
    })
    .catch((error) => {
      console.log("请求数据错误: ", error.message);
      showError(error.message);
    });
}

function showError(txt) {
  const error = document.querySelector(".error");
  error.innerHTML = txt;
  error.style.display = "flex";
  setTimeout(() => {
    error.style.display = "none";
  }, 2000);
}

function requestGet(url, body, callback) {
  return request(SERVER_HOME + url, { method: "GET", body }, callback);
}

function requestDelete(url) {
  return request(SERVER_HOME + url, { method: "DELETE" });
}

function requestPost(url, body, callback) {
  return request(SERVER_HOME + url, { method: "POST", body }, callback);
}

function requestPatch(url, body) {
  return request(SERVER_HOME + url, { method: "PATCH", body });
}

function requestPut(url, body) {
  return request(SERVER_HOME + url, { method: "PUT", body });
}
